var map, geolocation, marker, geocoder;
var w_height = $(window).height(); //整个页面高度

var _height = w_height - 64; //64是底部“展开更多”的高度

var pla = ismobile(1); //0:iPhone    1:Android
if (pla == 0) { //iphone里app的高度貌似少了20.所以在这里再减掉20.
	_height = _height - 20;
}

var t_height = -w_height * 0.24; //用于地图定位按钮和工具按钮的ranslateY偏移。
var geo_position = []; //定位坐标
var geo_position_error = []; //定位失败的时候默认的定位坐标

var currentPage = 1;
var totalPage = 1;

map = new AMap.Map('container', {
	resizeEnable: true,
	zoom: 8,
	resizeEnable: true
});
geocoder = new AMap.Geocoder({
	radius: 1000,
	extensions: "all"
});

//加载networks的点。
var markers = []; //存放加载的网点mark
var networks = []; //存放网点信息

var name = '景德镇';//getCookie('name') || ''; //进入页面时的初始查询条件。
console.log("name: " + name);
load_network(1, name);

function load_network(currentPage, name_s) {
	console.log("load networks begin")
	networks = [];
	$.ajax({
		url: "website/list",
		type: "GET",
		data: {
			"random": Math.random(),
			"currentPage": currentPage,
			"pageSize": 10,
			"name": name_s
		},
		dataType: 'json',
		async: false, //同步
		timeout: 10000,
		success: function(data) {
			console.log(data)
			var str = data.object;
			var html = '';
			totalPage = data.pager.totalPage;
			currentPage = data.pager.currentPage;
			if (str.length == 0) {
				$(".nodata_load").show();
				return false;
			}
			$(".nodata_load").removeAttr('style');
			geo_position_error = [str[0].longitude, str[0].latitude];
			// console.log(geo_position_error)
			for (var i = 0; i < str.length; i++) {
				networks[i] = {
					"lnglat": [str[i].longitude, str[i].latitude],
					"name": str[i].name,
					"address": str[i].address,
					"telephone": str[i].telephone.split(",")[0],
					"id": str[i].id,
					"distance": ''
				}
			}
		},
		error: function(data) {
			console.log(data);
			$(".nodata_load").show();
		}
	});
}

//点击地图时候返回坐标和地址
map.on('click', function(e) {

	this.longitude = e.lnglat.getLng();
	this.latitude = e.lnglat.getLat();

	geocoder.getAddress([this.longitude, this.latitude], function(status, result) {
		if (status === 'complete' && result.info === 'OK') {
			// 返回地址描述
			var address = result.regeocode.formattedAddress;
			console.log(address)
			return;
		}
	});
});

var isIOS;

function setIOS() {
	isIOS = true;
}

if (isIOS) {
	function IOS_getMessage(longitude, latitude) {
		geo_position = [longitude, latitude];
		// $(".searchbox").addClass('isIos');
		load();
	}

} else {
	try {
		var longitude = window.callJava.getMessage('longitude');
		var latitude = window.callJava.getMessage('latitude');
		geo_position = [longitude, latitude];
		load();

	} catch (e) {}

}

var t, s; //setInterval

function load() {
	console.log(geo_position)
	if (geo_position[0]) {
		new AMap.Marker({
			map: map,
			zIndex: 2,
			position: geo_position,
			offset: new AMap.Pixel(-45, -45), //相对于基点的位置
			content: '<div id="setAngle" style="transform:rotate(0deg)"><img src="website/img/location_mark.png" /></div>'
		});
		t = setInterval(function() {
			console.log("setInterval: until networks.length != 0")
			if (networks.length != 0) {
				clearInterval(t);
				loadmark(networks);
			}
		}, 1000);
		setTimeout(function() {
			console.log("Stop setInterval after 10 seconds.")
			clearInterval(t);
			$(".loading").hide();
		}, 10000);
	} else {
		t = setInterval(function() {
			console.log("setInterval: until networks.length != 0")
			if (networks.length != 0) {
				clearInterval(t);
				geo_position = geo_position_error;
				new AMap.Marker({
					map: map,
					zIndex: 2,
					position: geo_position,
					offset: new AMap.Pixel(-45, -45), //相对于基点的位置
					content: '<div id="setAngle" style="transform:rotate(0deg)"><img src="website/img/location_mark.png" /></div>'
				});
				loadmark(networks);
			}
		}, 1000);
		setTimeout(function() {
			console.log("Stop setInterval after 10 seconds.")
			clearInterval(t);
			$(".loading").hide();
		}, 10000);
	}
	// map.setZoom(11);
}
// load();



//工具条
map.plugin(["AMap.ToolBar"], function() {
	var tool = new AMap.ToolBar({
		offset: new AMap.Pixel(5, 90), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
		position: 'RB', //定位按钮停靠位置，默认：'LB'，左下角,“LT”：左上角 “RT”：右上角 “RB”：右下角
		// ruler: false, //标尺键盘是否可见，默认为true
		liteStyle: true, //是否使用精简模式，默认为false

	});
	map.addControl(tool);

	//设置工具条translateY初始值。
	transformCss(".amap-toolbar", t_height);
});
var amap_geolocation_con = '<div class="amap-geolocation-con" style="position: absolute; z-index: 9999; left: 5px; bottom: 10px;"><div class="amap-geo"><img src="website/img/location_btn.png"></div></div>';
$(".amap-controls").prepend(amap_geolocation_con);
transformCss(".amap-geolocation-con", t_height);

function loadmark(data, isSearch) {

	if (data.length == 0) {
		setTimeout(function() {
			$(".loading").hide();
			$(".nodata").show();
		}, 500);
		return false;
	}

	map.remove(markers);
	map.remove(marker_click);
	markers = [];
	marker_click = [];
	var lnglat = new AMap.LngLat(geo_position[0], geo_position[1]);
	var str = data;
	var new_str = [];

	for (var i = 0; i < str.length; i++) {
		if ((isNaN((str[i].lnglat)[0]))) {
			continue;
		}
		var distance = lnglat.distance(str[i].lnglat); //距离定位点
		distance = parseInt(distance);
		str[i].distance = distance;
		new_str.push(str[i]);
	}

	function down(x, y) {
		return (x.distance > y.distance) ? 1 : -1
	}
	//根据距离排序
	new_str.sort(down);
	str.sort(down);
	var html = '';
	if (currentPage != 1) {
		html = '<div class="page page_prev"><i class="i_loading none"></i>下拉加载上一页</div>';
	}

	for (var i = 0, marker; i < new_str.length; i++) {

		marker = new AMap.Marker({
			map: map,
			zIndex: 2,
			position: new_str[i].lnglat,
			offset: new AMap.Pixel(-18, -18), //相对于基点的位置
			icon: new AMap.Icon({
				size: new AMap.Size(36, 36),
				image: 'website/img/mark_normal.png'
			})
		});
		markers.push(marker);
		//设置对应点的点击信息
		marker.on('click', markerClick);

		//加载html列表
		html += '<div class="network_ele" id="' + str[i].id + '"><div class="title"><span class="text">';
		html += str[i].name;
		html += '</span><a class="detail"></a>';
		html += '<a class="phone" href="tel:' + str[i].telephone + '"></a>';
		html += '</div><div class="p">';
		html += '<span>' + str[i].name + '</span>';
		html += '<span class="address">' + str[i].address;
		html += '</span><span class="distance">' + (str[i].distance || 0) + '米</span></div></div>';
	}


	console.log("currentPage: " + currentPage)
	console.log("totalPage: " + totalPage)

	if (currentPage != totalPage) {
		html += '<div class="page page_next"><i class="i_loading none"></i>上拉加载下一页</div>'
	} else {
		html += '<div class="page page_next">没有更多记录了</div>';
	}

	$(".network_list > .list_box").html(html);

	html = '';
	if (currentPage != 1) {
		// $(".network_list").scrollTop(20);
	}

	var starty, endy; //页面拖动的时候使用。false的时候列表可以点击，true的时候列表不能点击。

	$(".network_ele").on("touchstart", function(event) {
		var event = event || window.event;
		starty = event.originalEvent.targetTouches[0].pageY;
	});
	$(".network_ele").on("touchend", function(event) {
		var event = event || window.event;
		endy = event.originalEvent.changedTouches[0].pageY;
		if (starty == endy) { //如果touch没有改变的话，则设置为true，可以点击跳转，否则不能点击跳转。
			var id = $(this).attr('id');
			var name = $("#search").val();

			if (event.target.className == "phone") {
				var phonehref = $(event.target).attr("href");
				console.log(phonehref);
				console.log(phonehref.substr(4))
				console.log(event.target.className);
				console.log(pla)
				if (pla == 1) { //Android端的时候增加一个弹出框
					var pop = "<div class='phone_pop'><div><p class='num'>" + phonehref.substr(4) + "</p><p class='btn'><span class='cancel'>取消</span><span class='call'>呼叫</span></p></div></div>"
					$("body").prepend(pop);
					$(".cancel").on("touchend", function() {
						$(".phone_pop").remove();
					})
					$(".call").on("touchend", function() {
						$(".phone_pop").remove();
						window.callJava.htmlCallJava(phonehref);
					})
				} else {
					window.location.href = phonehref;
				}
				return false;
			}
			window.location.href = 'detail.html?id=' + id;
		}
	});

	map.setZoom(11);
	if (isSearch) {
		// new_str[0].lnglat；//查询出来的坐标组里，经过排序后的第一个坐标。	
		map.setCenter(new_str[0].lnglat);
	} else {
		map.setCenter(geo_position);
	}
	$(".loading").hide();
	$(".search_wrap").removeClass('focus');
	$(".i_loading").addClass('none');
}

var marker_click = []; //存放点击时候显示的mark点
var ismarkerclick = true; //只在第一次点击mark点的时候记录定位图标和工具条的偏移值，点击back_list的时候重置。
var t_css = ''; //记录点击前定位图标和工具条的偏移值。
//点击信息点时改变图标
function markerClick(e) {

	var j = markers.indexOf(e.target); //在数组中的index
	var id = $(".network_ele").eq(j).attr("id");
	window.location.href = 'detail.html?id=' + id;

	return false;


	for (var i = 0; i < markers.length; i++) {
		markers[i].show();
	}
	markers[j].hide();

	map.remove(marker_click);
	marker = new AMap.Marker({ //添加自定义点标记
		map: map,
		position: e.target.getPosition(), //基点位置
		offset: new AMap.Pixel(-20, -57), //相对于基点的偏移位置
		draggable: false, //是否可拖动
		content: '<div><img src="website/img/mark_click.png" /></div>' //自定义点标记覆盖物内容
	});
	marker_click.push(marker);
	// 设置中心点
	map.setCenter(e.target.getPosition());

	if (ismarkerclick) {
		t_css = $(".amap-geolocation-con").css("transform");
	}
	ismarkerclick = false;

	$(".network_list").hide().removeClass('up').removeClass('down');
	$(".network_active").html($(".network_ele").eq(j).clone());



	$(".network_active .network_ele").on("touchend", function(event) {
		var event = event || window.event;
		var id = $(this).attr('id');
		var name = $("#search").val();
		console.log(event.target.className)
		if (event.target.className == "phone") {
			var phonehref = $(event.target).attr("href");
			console.log(phonehref);
			console.log(phonehref.substr(4))
			console.log(event.target.className);
			console.log(pla)
			if (pla == 1) { //Android端的时候增加一个弹出框
				var pop = "<div class='phone_pop'><div><p class='num'>" + phonehref.substr(4) + "</p><p class='btn'><span class='cancel'>取消</span><span class='call'>呼叫</span></p></div></div>"
				$("body").prepend(pop);
				$(".cancel").on("touchend", function() {
					$(".phone_pop").remove();
				})
				$(".call").on("touchend", function() {
					$(".phone_pop").remove();
					window.callJava.htmlCallJava(phonehref);
				})
			} else {
				window.location.href = phonehref;
			}
			return false;
		}
		window.location.href = 'detail.html?id=' + id;
	});

	transformCss("#container", -83);

	//根据网点名称信息内容多少改变定位点和工具条的布局。
	var nn = 108 - $(".network_active .network_ele").outerHeight() - 35;
	transformCss(".amap-geolocation-con, .amap-toolbar", nn);

	$(".back_list").show();
	$(".back_page").hide();

	$(".back_list").click(function() {
		ismarkerclick = true;
		// map.setFitView();
		// map.setZoom(map.getZoom() - 1);

		markers[j].show(); //显示点击时候隐藏的点
		map.remove(marker_click); //删除点击产生的新增点

		$("#container").removeAttr('style');

		$(".amap-geolocation-con, .amap-toolbar").css({
			"-webkit-transform": t_css,
			"-moz-transform": t_css,
			"-ms-transform": t_css,
			"-o-transform": t_css,
			"transform": t_css
		});

		$(".network_list, .back_page").show();
		$(".back_list").hide();
		$(".network_active").html("");
	});
}


// 设备方向定位, 手机上有效
function handleOrientation(event) {
	var north = event.webkitCompassHeading || (360 - event.alpha); //移动Safari时，Alpha基于设备首次请求设备时的指向方向。 罗盘方向使用webkitCompassHeading。
	//设置地图定位按钮translateY初始值。    
	$("#setAngle").css({
		"-webkit-transform": "rotate(" + north + "deg)",
		"-moz-transform": "rotate(" + north + "deg)",
		"-ms-transform": "rotate(" + north + "deg)",
		"-o-transform": "rotate(" + north + "deg)",
		"transform": "rotate(" + north + "deg)"
	});
}
window.addEventListener('deviceorientation', handleOrientation);

//加载搜索列表
function search_list_html(data) {
	var html = '';
	for (var i = 0; i < data.length; i++) {
		html += '<li><i class="point"></i><p class="title">';
		html += data[i].name;
		html += '</p><p class="text">';
		html += data[i].address;
		html += '</p><i class="arrow"></i></li>';
	}
	$(".search_list ul").html(html);
	$(".search_list li").click(function() {
		var elem = $(this);
		console.log("点击列表开始搜索")
		var name = elem.find(".title").text();
		setCookie('name', name, 1);
		$("#search").val(name);
		$(".loading").show();
		load_network(1, name);
		loadmark(networks, true);
		elem.prependTo(elem.parent());
		//设置地图定位按钮translateY初始值。    
		transformCss(".amap-geolocation-con", t_height);
		$(".network_list ").attr("class", "network_list pos_2");
		$(".network_list .tip").show();
		$(".searchbox").removeClass('cover');
	})
}

$(function() {

	$("#search").val(name);

	$("#searchbtn").click(function() {
		var name = $("#search").val();
		if (!name) {
			return false;
		}
		setCookie('name', name, 1);

		$(".loading").show();
		console.log("name: " + name);
		load_network(1, name);
		loadmark(networks, true);

		//设置地图定位按钮translateY初始值。 
		transformCss(".amap-geolocation-con", t_height);

		$(".network_list ").attr("class", "network_list pos_2");
		$(".network_list .tip").show();
		$(".searchbox").removeClass('cover');

	});

	$("#search").focus(function() {
		var elem = $(this);
		var name = elem.val();
		elem.closest('.search_wrap').addClass('focus');
		$(".back_list, .back_page").removeAttr('style');
		if (name != '' && $(".search_list li").length == 0) {
			search_list_html(networks);
		}


	});

	var ajaxCache = {}; //定义缓存对象
	var ajaxtimeout = 0;
	$("#search").on("input paste", function() {
		var elem = $(this);
		var name = elem.val();

		clearTimeout(ajaxtimeout);
		ajaxtimeout = setTimeout(function() {
			if (!!ajaxCache[name]) {
				networks = ajaxCache[name];
				search_list_html(networks);
			} else {
				load_network(1, name);
				search_list_html(networks);
				ajaxCache[name] = networks;
			}
		}, 500);

	});

})

$(".amap-geolocation-con").click(function() {
	map.setCenter(geo_position);
});

//返回上一页
$(".back_page").click(function() {
	clearCookie();

});

//清除所有cookie。
function clearCookie() {
	var keys = document.cookie.match(/[^ =;]+(?=\=)/g);
	if (keys) {
		for (var i = keys.length; i--;)
			document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString()
	}
}